package first.endtoend

import first.endtoend.messages.MessageCode
import grails.converters.JSON
import org.springframework.dao.DataIntegrityViolationException

class ProductController
{
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def scaffold = true


    def index()
    {
        redirect(action: "list", params: params)
    }

    def list(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        [productInstanceList: Product.list(params), productInstanceTotal: Product.count()]
    }

    def create()
    {
        [productInstance: new Product(params)]
    }

    def save()
    {
        println params
        def f = request.getFile('fileIcon')
        if (f.empty)
        {
            flash.message = 'file is empty'
            render(view: 'edit')
            return
        }
        def path = grailsApplication.config.productPhotos + params.name + ".jpg"
        println("FileDest = " + path)
        f.transferTo(new File(path))


        def productInstance = new Product(params)
        productInstance.iconURL = fileDest.getName()
        if (!productInstance.save(flush: true))
        {
            render(view: "create", model: [productInstance: productInstance])
            return
        }

        //here try to save a notification in DB

        Notification notificationInstance = new Notification(idModel: productInstance.id, code: MessageCode.PRODUCT_ADD.value(), modelName: Product.getSimpleName(), description: message(code: 'product.add.notificiation.message' + productInstance.name, default: "There is a new Product added")).save()
        /* List<Long> listId= new ArrayList<Long>()
         listId.add(productInstance.id)
         NotificationView notification=new NotificationView()
         notification.code=MessageCode.PRODUCT_ADD.value()
         notification.data=listId

         JSONObject jsonNotif=JsonHelper.createJsonObject(notification)

         List<Agent> listAgent=Agent.executeQuery("select a from Agent a where a.regId IS NOT NULL")
         sendNotificationService.sendNotificationToAll(listAgent,jsonNotif.toString())*/

        flash.message = message(code: 'default.created.message', args: [message(code: 'product.label', default: 'Product'), productInstance.id])
        redirect(action: "show", id: productInstance.id)
        //here free session["pathImg"]
        session["pathImg"] = null
    }

    def showAjax(Long id)
    {
        def productInstance = Product.get(id)

    }

    def show(Long id)
    {
        def productInstance = Product.get(id)
        if (!productInstance)
        {
            if (request.xhr)
            {
                render([code: MessageCode.NOT_FOUND.value()] as JSON)
                return
            }
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), id])
            redirect(action: "list")
            return
        }
        if (request.xhr)
        {
            render([data: productInstance, code: MessageCode.SUCCESS.value()] as JSON)
            return
        }
        [productInstance: productInstance]
    }

    def edit(Long id)
    {
        def productInstance = Product.get(id)



        if (!productInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), id])
            redirect(action: "list")
            return
        }

        [productInstance: productInstance]
    }


    def update(Long id, Long version)
    {
        println("dans update " + session["pathImg"])
        def productInstance = Product.get(id)
        if (!productInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), id])
            redirect(action: "list")
            return
        }
        def f = params.fileIcon
        if (f == null)
        {
            flash.message = 'file is empty'
            render(view: 'edit')
            return
        }

        def path = grailsApplication.config.productPhotos + params.name + ".jpg"
        println("FileDest = " + path)
        f.transferTo(new File(path))

        productInstance.iconURL = params.name + ".jpg"
        println("ICONURL ==== " + productInstance.iconURL)
        if (version != null)
        {
            if (productInstance.version > version)
            {
                productInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'product.label', default: 'Product')] as Object[],
                        "Another user has updated this Product while you were editing")
                render(view: "edit", model: [productInstance: productInstance])
                return
            }
        }

        productInstance.properties = params
        if (!productInstance.save(flush: true))
        {
            render(view: "edit", model: [productInstance: productInstance])
            return
        }

        Notification notificationInstance = new Notification(idModel: productInstance.id, code: MessageCode.PRODUCT_UPDATE.value(), modelName: Product.getSimpleName(), description: message(code: 'product.update.notification.message' + productInstance.name, default: "There is an update of a product")).save()
        println("here my notif is" + notificationInstance)


        flash.message = message(code: 'default.updated.message', args: [message(code: 'product.label', default: 'Product'), productInstance.id])
        redirect(action: "show", id: productInstance.id)
        session["pathImg"] = null
    }

    def delete(Long id)
    {
        def productInstance = Product.get(id)
        if (!productInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), id])
            redirect(action: "list")
            return
        }

        /* List<Long> listId= new ArrayList<Long>()
         listId.add(productInstance.id)
         NotificationView notification=new NotificationView()
         notification.code=MessageCode.PRODUCT_DELETE.value()
         notification.data=listId

         JSONObject jsonNotif=JsonHelper.createJsonObject(notification)

         List<Agent> listAgent=Agent.executeQuery("select a from Agent a where a.regId IS NOT NULL")
         sendNotificationService.sendNotificationToAll(listAgent,jsonNotif.toString())*/
        try
        {
            productInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'product.label', default: 'Product'), id])
            Notification notificationInstance = new Notification(idModel: productInstance.id, code: MessageCode.PRODUCT_DELETE.value(), modelName: Product.getSimpleName(), description: message(code: 'product.delete.notification.message' + productInstance.name, default: "There is a delete of a product")).save()

            redirect(action: "list")

        }
        catch (DataIntegrityViolationException e)
        {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'product.label', default: 'Product'), id])
            redirect(action: "show", id: id)
        }
    }


}
